package com.zhenai.rocyuan.modules.threadupdown.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.log4j.Logger;

import com.zhenai.rocyuan.modules.threadupdown.BaseSocket;

public class ServerAction {
	private Logger log = Logger.getLogger(this.getClass());

	/**
	 * 服务器开始监听入口
	 * 
	 * @param port
	 *            服务器监听端口
	 * @param file
	 *            本次服务器要下载给客户端的文件
	 */
	private void acceptConnection(int port) {
		ServerSocket server = null;
		try {
			server = new ServerSocket(port, BaseSocket.MAX_CONN_COUNT);
			while (true) {
				Socket socket = server.accept();
				socket.setTcpNoDelay(true);
				HandelMain.processRequest(socket);
			}
		} catch (java.net.BindException e) {
			log.error(e, e);
			log.error("端口号被占用");
			return;
		} catch (IOException e) {
			log.error(e, e);
		} finally {
			if (server != null) {
				try {
					server.close();
				} catch (IOException e) {
					log.error(e, e);
				}
			}
		}
	}

	/**
	 * 服务器监听初始化，等待客户端连接
	 * 
	 * @param port
	 * @param file
	 */
	public void init(int port) {
		for (int i = 0; i < BaseSocket.MAX_CONN_COUNT; i++) {
			HandelMain h = new HandelMain();
			new Thread(h, BaseSocket.THREAD_NAME + i).start();
		}
		this.acceptConnection(port);
	}

	/**
	 * 启动服务器程序
	 * 
	 * @param arg
	 */
	public static void main(String arg[]) {
		new ServerAction().init(BaseSocket.SERVER_PORT);
	}
}
